#!/usr/local/bin/perl

# A simple script that uses the Twittervision API to fetch
# locations and display them on a Google Static Map.

# By Per Henrik Johansen <per.henrik.johansen@gmail.com>

use strict;
use warnings;
use LWP::UserAgent;
use GD;
use WWW::Twittervision;
 
# --- Config ----------------------------

my $google_api_key = "put_your_api_key_here";

# --- NO NEED TO EDIT BELOW THIS POINT --

use Getopt::Lazy
	'width|width=i' => ['[INTEGER] The width of the map' => 256],
	'height|height=i' => ['[INTEGER] The height of the map' => 160],
	'zoom|zoom=i' => ['[INTEGER] The zoom level of the map'],
	-summary => 'Makes a small map showing the location of twitter screen names',
	-usage => '%c %o screen_name1 [more_screen_names]',
        ;

GetOptions;
Getopt::Lazy::show_help() and exit 1 unless @ARGV;

my $markers = "";
my $tv = new WWW::Twittervision();

foreach my $screen_name (@ARGV) {
	my $info = $tv->current_status(screen_name => $screen_name);
	
	my $lon = undef;
	my $lat = undef;
	
	if(defined($info->{location}->{longitude})) {
		$lon = $info->{location}->{longitude};
	}
	if(defined($info->{last_status}->{'text'})) {
		$lat = $info->{location}->{latitude};
	}
	
	if(!$lat || !$lon) {
		next;
	}
	$ markers .= $lat . ',' . $lon . ',red|';
}

chop $markers;
$width = ($width > 512 ? 512 : $width);
$height = ($height >512 ? 512 : $height);
my $mapurl = 
	'http://maps.google.com/staticmap?' .
	($zoom ? 'zoom=' . $zoom . '&' : '' ). 
	'size=' . $width . 'x' . $height .'&' . 
	'markers=' . $markers . '&' .
	'key=' . $google_api_key;

my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(GET => $mapurl);
my $res = $ua->request($req);

my $mapimage;

if ($res->is_success) {
	$mapimage = GD::Image->newFromGifData($res->content);
}  else {
        print STDERR "Could not get map\n";
	exit;
}

print $mapimage->gif;